<?php

namespace app\store\controller;

use app\admin\common\Base;
use think\Db;
use app\admin\common\Excel;

//其他入出库单
class Invoiout extends Base
{
    public function index()
    {

        $data = $this->request->param();

        $this->assign('o_type',8);//高级搜索状态（8：其他出库单记录）

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);


            if ($map == '') {
                $list = Db::name('stock_record')->where('o_type', 1)->where('o_way', 3)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('stock_record')->where('o_type', 1)->where('o_way', 3)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('stock_record')->where('o_type', 1)->where('o_way', 3)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('stock_record')->where('o_type', 1)->where('o_way', 3)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }
            foreach ($list as $key => &$val) {
                $val['dj_time'] = date('Y-m-d', $val['dj_time']);
                $val['type_name'] = $val['type'] == 0 ? '其它出库' : '盘亏';
                $c = Db::name('customer')->where('id', $val['user_id'])->find();
                $val['customer_name'] = $c['sn'] . ' ' . $c['name'];
                $val['shuliang'] = Db::name('stock_record_good')->where('pid', $val['id'])->sum('number');
                $val['add_user_name'] = $val['add_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['add_user'])->value('name');
                $val['shenhe_user_name'] = $val['shenhe_user'] == 0 ? '' : Db::name('auth_user')->where('id', $val['shenhe_user'])->value('name');
            }

            return $this->grid_data($list, $count, $page, $limit);
        }
        $today = date('Y-m-d', time());
        $mon_start = date('Y-m', time()) . '-01';
        $this->assign('today', $today);
        $this->assign('mon_start', $mon_start);
        return $this->fetch();
    }




    public function add()
    {
        $sn = osn('QTCK', 3);
        $today = date('Y-m-d', time());
        $store = Db::name('store')->where('is_del', 0)->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id asc')->select();
        $this->assign('store', $store);
        $this->assign('today', $today);
        $this->assign('sn', $sn);
        return $this->fetch();
    }

    public function edit()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {

            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('check_details')->where('pid', $data['pid'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->where('difference', '<', 0)->select();
            $count = Db::name('check_details')->where('pid', $data['pid'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->where('difference', '<', 0)->count();

            $ii=0;
            foreach ($list as $key => &$value) {
                $value['o_id'] = $value['id'];
                $goods = Db::name('goods')->where('id', $value['goods_id'])->find();
                $list[$key]['goodsname'] = $goods['name'];
                $list[$key]['dw'] = Db::name('unit')->where('id', $value['unit_id'])->value('name');
                $list[$key]['store_name'] = Db::name('store')->where('id', $value['store_id'])->value('name');
                $list[$key]['use_ck'] = $value['stock'];
                $list[$key]['number'] = abs($value['difference']);
                $list[$key]['price'] = Db::name('goods_price_strategy')->where('goods_id', $value['goods_id'])->value('sale_price');
                $list[$key]['jine'] = $list[$key]['number'] * $list[$key]['price'];
                $list[$key]['good_id'] = $value['goods_id'];
                $list[$key]['store_id'] = $value['store_id'];
                $list[$key]['unit_id'] = $value['unit_id'];
                $value['id']=$ii+1;
                $ii+=1;
            }

            //少于5条则填充
            if (5 - $count > 0) {
                for ($i = 0; $i < 5 - $count; $i++) {
                    array_push($list, ['id'=>$count+$i+1]);
                }
            }
            return $this->grid_data($list, $count, $page, $limit);
        }

        $sn = osn('QTCK', 3);
        $today = date('Y-m-d', time());
        $store = Db::name('store')->where('is_del', 0)->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id asc')->select();
        $this->assign('store', $store);
        $this->assign('today', $today);
        $this->assign('sn', $sn);
        $this->assign('pid', $data['pid']);
        return $this->fetch();
    }


    // 添加调拨单-更新
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $isPandian = false;
        if (isset($data['pandian']) && !empty($data['pandian'])) {
            $isPandian = true;
            $sn = $data['sn'];
            $check_id = $data['pandian'];
            $pandiantype = $data['pandiantype'];
            unset($data['pandian']);
            unset($data['pandiantype']);
        }
        // halt($pid);
        Db::startTrans(); // 启动事务
        $res = $this->inset_stock_record($data, 1, 3, $pid = 0, $psn = null);
        if ($res == 1) {
            if ($isPandian) {
                $result = Db::name('check')->where('id', $check_id)->value('result');
                $resultstr = $pandiantype . ' ' . $sn;
                if (!empty($result)) {
                    $resultstr = $result . ',' . $pandiantype . ' ' . $sn;
                }
                $res1 = Db::name('check')->where('id', $check_id)->update(['result' => $resultstr]);
                // halt($res1);
                if (!$res1) {
                    Db::rollback(); // 回滚事务
                    $msg = '盘点主表关联失败';
                } else {
                    Db::commit(); // 提交事务
                    $status = 1;
                    $msg = "添加成功";
                }
            } else {
                Db::commit(); // 提交事务
                $status = 1;
                $msg = "添加成功";
            }
        } else if ($res == 2) {
            Db::rollback(); // 回滚事务
            $msg = "存在相同的单据号";
        } else {
            Db::rollback(); // 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }


    //审核与反审核
    public function shenhe()
    {
        $data = $this->request->param();
        $status = 0;
        $msg = "操作失败";
        $id = $data['id'];
        $type = $data['type'];
        // 启动事务
        Db::startTrans();
        $info = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->find();
        //if($info['xhdd_id']==0&&$info['xht_id']==0&&$info['xh_id']==0){
        if ($type == 1) {
            $update = [
                'status' => 1,
                'updatetime' => time(),
                'shenhe_time' => time(),
                'shenhe_user' => $this->Userinfo['id'],
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
        }
        if ($type == 2) {
            $update = [
                'status' => 0,
                'updatetime' => time(),
                'shenhe_time' => 0,
                'shenhe_user' => 0,
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
        }
        if ($result) {
            // 提交事务
            Db::commit();
            $status = 1;
            $msg = "操作成功";
        }
        // }else{
        //     $msg="存在关联单据不能操作";
        // }
        if ($status != 1) {
            // 回滚事务
            Db::rollback();
        }
        return ['status' => $status, 'msg' => $msg];
    }

    //删除
    public function del($id)
    {
        $status = 0;
        $msg = "删除失败";
        // 启动事务
        Db::startTrans();
        $info = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->find();
        // halt( $info);
        if ($info['pid'] == 0 && empty($info['psn'])) {
            $update = [
                'is_del' => 1,
                'updatetime' => time(),
                'last_user' => $this->Userinfo['id'],
            ];
            $result = Db::name('stock_record')->where('id', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->update($update);
            if ($result) {
                $res = Db::name('stock_record_good')->where('pid', $id)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->setField('is_del', 1);
                if ($res) {
                    // 提交事务
                    Db::commit();
                    $status = 1;
                    $msg = "删除成功";
                }
            }
        } else {
            $msg = "存在关联单据不能删除";
        }

        if ($status != 1) {
            // 回滚事务
            Db::rollback();
        }
        return ['status' => $status, 'msg' => $msg];
    }
    //订单详情
    public function details()
    {
        $data = $this->request->param();
        $oid = $data['record_id'];
        $o = Db::name('stock_record')->where('id', $oid)->where('is_del', 0)->find();
        $customer = Db::name('customer')->where('id', $o['user_id'])->find();
        $o['customer_name'] = $customer['sn'] . ' ' . $customer['name'];
        $o['customer_id'] = $customer['id'];

        //halt($o);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if ($map == '') {
                $list = Db::name('stock_record_good')->where('pid', $oid)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('addtime desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('stock_record_good')->where('pid', $oid)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('stock_record_good')->where('pid', $oid)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('stock_record_good')->where('pid', $oid)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }

            $ii=0;
            foreach ($list as $key => &$val) {
                $val['o_id'] = $val['id'];
                $g = Db::name('goods')->where('id', $val['good_id'])->find(); //商品
                $c = Db::name('store')->where('id', $val['store_id'])->find(); //仓库
                $val['goodsname'] = $g['name'];
                $val['dw'] = Db::name('unit')->where('id', $val['unit_id'])->value('name'); //仓库
                $val['store_name'] = $c['name'];
                $val['id']=$ii+1;
                $ii+=1;
            }
            //少于5条则填充
            if (5 - $count > 0) {
                for ($i = 0; $i < 5 - $count; $i++) {
                    array_push($list, ['id'=>$count+$i+1]);
                }
            }
            return $this->grid_data($list, $count, $page, $limit);
        }


        //仓库
        $store = Db::name('store')->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id desc')->select();
        $this->assign('store', $store);
        $this->assign('info', $o);
        return $this->fetch();
    }
    //导出
    public function export() {
        $data = $this->request->param();
        $rowid = explode(" ",$data['rowid']);

        $title = [
            'dj_time' => '单据日期',
            'sn' => '单据编号',
            'type' => '业务类别',
            'total_price' => '总金额',
            'user_id' => '供应商',
            'add_user' => '制单人',
            'shenhe_user' => '审核人',
            'mark' => '备注',
            'print_number'=>'打印次数',
            'goods_sn'=>'商品编码',
            'goods_name'=>'商品名称',
            'goods_model'=>'规格型号',
            'goods_code'=>'商品条码',
            'goods_attribute'=>'属性',
            'unit_id'=>'单位',
            'number'=>'数量',
            'price'=>'入库单价',
            'jine'=>'入库金额',
            'store_id'=>'仓库',
            'zmark'=>'备注',
        ]; 
        $a = '';
        $arr_list = [];
        //查询子表
        $list = Db::name('stock_record_good')->alias('a')->join('stock_record b','a.pid = b.id')->where('a.pid','in',$rowid)->where('a.is_del', 0)->where('b.o_type', 1)->where('b.o_way', 3)->where('a.enterprise_id', $this->EnterpriseId)->order('b.id desc')->select();
        //子表遍历输出的内容
        foreach ($list as $k=>&$v) {
            //查询商品表追加内容
            $v['dj_time'] = date('Y-m-d',$v['dj_time']);
            $v['zmark'] = db('stock_record_good')->where('is_del',0)->where('pid',$v['id'])->value('mark');
            $goods = db('goods')->where('is_del',0)->where($this->EnterpriseId)->where('id',$v['good_id'])->find();
            $v['goods_sn'] = $goods['sn'];
            $v['goods_name'] = $goods['name'];
            $v['goods_model'] = $goods['model'];
            $v['goods_attribute'] = $goods['attribute'];
            $v['goods_code'] = $goods['code'];
            $v['user_id'] = db('customer')->where('id', $v['user_id'])->value('name');
            $v['unit_id'] = db('unit')->where('id', $v['unit_id'])->value('name');
            $v['store_id'] = db('store')->where('id',$v['store_id'])->value('name');
            $v['type'] = $v['type'] == 0 ? '其他' :  '盘亏';
            array_push($arr_list,$v);
            //追加空格行 输出 合计
            $a = empty($a) ? $a =['id'=>'0']  : $a ;
            if ($a['id'] !== $v['id']) {
                //计算总数;
                $hj = [
                    'id' =>$v['id']-1,
                    'dj_time' => '',
                    'sn' => $v['sn'],
                    'type' => '',
                    'total_price' => '',
                    'user_id' => '',
                    'add_user' => '',
                    'shenhe_user' => '',
                    'mark' => '',
                    'print_number'=>'',
                    'goods_sn'=>'合计',
                    'goods_name'=>'',
                    'goods_model'=>'',
                    'goods_code'=>'',
                    'goods_attribute'=>'',
                    'unit_id'=>'',
                    'number'=>'',
                    'price'=>'',
                    'jine'=>'',
                    'store_id'=>'',
                    'zmark'=>'',
                ];
                $hj['number'] = db('stock_record_good')->where('is_del',0)->where('pid',$v['id'])->sum('number'); 
                array_push($arr_list,$hj);
            }
            $a = $v;
        }
        array_multisort(array_column($arr_list,'id'), SORT_DESC, $arr_list);//按照ID大小排序
        // halt($arr_list);
            //添加标题到数组头部
            array_unshift($arr_list,$title);
            $kong_arr=$title;
            foreach ($kong_arr as $ke1 => $va1) {
                $kong_arr[$ke1]='';
            }
            for ($i=0; $i <3 ; $i++) { 
                array_unshift($arr_list,$kong_arr);
            }
             //根据此参数获取数据中的值，要与表格标题键名对应
            $keys=[];
            foreach ($title as $k2 => $v2) {
                array_push($keys, $k2);
            }
            $merge=[];
            $options=[];
            $o_type=-1;
            $merge=[//合并
            'start'=>5,
            'arr_zimu'=>['A','B','C','D','E','F','G','H','I'],
            'keyword'=>'sn',
        ];
        $options=[
                'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'],//居中
                'bold'=>['A1:T3','A4:T4'],//加粗
                'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
            ];
            $title=[//标题
            'title'=>"其他出库单",
            'max_zimu'=>"T",
            'number'=>'3',
        ];
            $excel_export_title="其他出库单_" . date('Y-m-d_His') . '.xlsx';//文件名称
            $excel = new Excel();
            $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,$o_type,$merge,$title);
            
            exit();
    }
}
